<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace ApiModule;

use ApiModule\BasePresenter;
use Nette\Application\Presenter;
use Albireo\Forms\AlbireoForm;
use Nette\Security\AuthenticationException;
use Albireo\OAuthServer\Token;
use Albireo\OAuthServer\OAuthServer;
use Albireo\OAuthServer\Users;

/**
 * Rest presenter.
 * Does not have to check parameters
 * rpcManagement have to take care of it
 *
 * This API supports DELETE, PUT also but you can work only with GET or POST if you need by specifying actions
 * @author     petr
 * @package    Api
 */
//TODO: needs refactoring and put in model
class AuthPresenter extends BasePresenter {

    private $oauth;
    private $token;
    private $sentToken;

    public function startup() {
        parent::startup();
        $this->oauth = new OAuthAccess();
    }

    public function actionDefault($token) {
        if (!$this->getUser()->isLoggedIn()) {
            throw new AuthenticationException("User is not logged in");
        }
        if (!isset($token) || empty($token)) {
            throw new \Exception("You are not supposed to be here");
        }
        $this->token = Token::findByToken($token);
        $this->sentToken = $token;
        if (!is_object($this->token) || !$this->token->isRequest()) {
            throw new \Exception("This token does not exist");
        }
    }

    protected function createComponentConfirmAppForm() {
        //todo: add captcha.
        //todo: need to register to create app
        $form = new AlbireoForm(NULL, "submit");

        $form->addSubmit('send', 'Register');

        $form->onSubmit[] = callback($this, 'formSubmitted');
        return $form;
    }

    public function formSubmitted($form) {
        $this->token->setVerifier(OAuthServer::generateVerifier($this->sentToken));
        $this->token->setUser(new User($this->getUser()->getIdentity()->id));
        $this->redirectUri($request_token->getCallback() . "?&oauth_token=" . $this->sentToken . "&verifier_token=" . $request_token->getVerifier());
    }

}